import React from 'react'

import axios from 'axios'
import PubSub from 'pubsub-js'
import {Ivegetable} from '../index'
import style from './index.module.css'
import {Toast} from "antd-mobile";
const {discountItem,shoppingCart,price,beforePrice,occluder,name} = style

export interface Imessage {
    acknowledged:boolean,
    matchedCount:number,
    modifiedCount:number,
    shoppingCartLength?:number
}

export default function DiscountItem(props:Ivegetable){
    //TODO:addShoppingCart1
    async function addShoppingCart() {
        const result = await axios.put(`/api/addshoppingcart/${props._id}`)
        const message = result.data as Imessage
        if(message.acknowledged){
            Toast.show({
                content:'添加购物车成功',
                position:'top'
            })
            PubSub.publish('cartLength',message.shoppingCartLength)
        }else {
            Toast.show({
                content:'购物车中已存在',
                position:'top'
            })
        }
    }

    return (
        <li className={discountItem}>
            <div>
                <img src={props.address} alt="" />
            </div>
            <div>
                <p className={name}>{props.name}</p>
                <div>
                    <div>
                        <p className={price}><span>¥</span><span>{props.price}</span></p>
                        <p className={beforePrice}>{props.beforePrice}</p>
                    </div>
                    <div className={shoppingCart} onClick={addShoppingCart}/>
                </div>
            </div>
            {
                props.soldOut && <div className={occluder}>已抢光</div>
            }
        </li>
    )
}